<template>
  <div id="express">
    <!--搜索-->
    <div class="search-content">
      <div>
        <el-input v-model="searchId" placeholder="输入ID查询" prefix-icon="el-icon-search" clearable style="width: 200px"  @change="inquiryList"/>
        <el-input v-model="searchPath" placeholder="输入路径查询" prefix-icon="el-icon-search" clearable style="width: 200px"  @change="inquiryList"/>
        <el-date-picker
          v-model="dateTimeRange"
          type="datetimerange"
          range-separator="至"
          clearable
          value-format="yyyy-MM-dd HH-mm-ss"
          @change="inquiryList"
          :picker-options="pickerOptions"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button type="primary" icon="el-icon-search" @click="inquiryList">查询</el-button>
      </div>
      <div class="search-apply">
        <el-button type="warning" icon="el-icon-edit" @click="addUpload">新增</el-button>
      </div>
    </div>
    <!--操作列表-->
    <div class="table">
      <el-table fit :data="tableData" style="width: 100%">
        <el-table-column label="ID" prop="id" align="center" width="60"/>
        <el-table-column label="价格" prop="price" align="center" width="100"/>
        <el-table-column label="表情路径" prop="path" align="center" width="600" />
        <el-table-column label="表情图片" prop="httpPath" align="center" width="100">
          <template slot-scope="scope">
            <img v-if='scope.row.httpPath' width="50" height='50' :src="scope.row.httpPath" alt="头像有误"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createDate" width="170" align="center"/>
        <el-table-column label="修改时间" prop="modifyDate" width="170" align="center"/>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="dealwithEdit(scope.$index, scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="dealwithDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <div class="pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="[10,20,30,40,50]"
          layout="total,sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!--新增蒙层-->
    <el-dialog id="add-dialog" title="新增" :visible.sync="addDialogVisible">
      <el-form label-position="right" label-width="30%" :model="add" :rules="addRules" ref="addRuleForm">
        <el-form-item label="表情图片：">
          <el-upload
            :with-credentials="true"
            :action=addGiftPath
            ref="addUpload"
            :limit="1"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture"
            name="file"
            :accept="formatFile"
            :on-success="addSuccess"
            :on-error="addError">
            <el-button size="small" type="warning">选择文件</el-button>
            <span class="uploadTips">{{uploadTip}}</span>
          </el-upload>
        </el-form-item>
        <el-form-item label="表情价格：" prop="price">
          <el-input v-model="add.price" placeholder="请输入表情价格" clearable/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button id="add-btn" type="primary" @click="addSubmit('addRuleForm')">新 增</el-button>
      </span>
    </el-dialog>
    <!--修改蒙层-->
    <el-dialog id="edit-dialog" title="修改" :visible.sync="editDialogVisible">
      <el-form label-position="right" label-width="30%" :model="edit" :rules="editRules" ref="editRuleForm">
        <el-form-item label="表情图片：">
          <el-upload
            :with-credentials="true"
            :action=addGiftPath
            ref="editUpload"
            :limit="1"
            :before-remove="beforeRemove"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :file-list="editFileList"
            list-type="picture"
            name="file"
            :accept="formatFile"
            :on-success="editSuccess"
            :on-error="editError">
            <el-button size="small" type="warning">选择文件</el-button>
            <span class="uploadTips">{{uploadTip}}</span>
          </el-upload>
          <img v-if="isShow" :src="editImage" width="50" height="50" style="margin-top:10px;" alt="图片有误"/>
        </el-form-item>
        <el-form-item label="表情价格：" prop="price">
          <el-input v-model="edit.price" placeholder="请输入表情价格" clearable/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button id="edit-btn" type="primary" @click="editSubmit('editRuleForm')">修 改</el-button>
      </span>
    </el-dialog>
    <!--删除-->
    <el-dialog :visible.sync="delDialogVisible" width="300px" center id="del-dialog" top="20%">
      <span>您确定要删除吗？</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="delDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="delKeys">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
  import {Message, Loading} from 'element-ui';
  import request from "../../utils/request";
  import axios from 'axios'
  import {baseUrl} from '../../settings'

  export default {
    name: "expressionlist",
    data() {
      var checkPublic = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('礼物名称不能为空'));
        } else {
          callback();
        }
      };
      var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('礼物价格不能为空'));
        } else if (!/^[1-9]\d*$/.test(value)) {
          return callback(new Error('礼物价格只能是正整数'));
        } else {
          callback();
        }
      };
      return {
        // 查询
        searchId: '',
        searchPath: null,
        dateTimeRange: [],
        pickerOptions: {
          shortcuts: [
            {
              text: '今天',
              onClick(picker) {
                const end = new Date();
                const start = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 0, 0, 0);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '本月',
              onClick(picker) {
                const end = new Date();
                const start = new Date(end.getFullYear(), end.getMonth(), 1, 0, 0, 0);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '上月',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
                let start = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0);
                let end = new Date(new Date().getFullYear(), new Date().getMonth(), 1, 23, 59, 59);
                end.setTime(end.getTime() - 3600 * 24 * 1000);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近三个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit('pick', [start, end]);
              }
            }
          ]
        },
        // 列表数据
        tableData: [],
        //新增
        addDialogVisible: false,
        addGiftPath: baseUrl + "admin/file/upload/expression",
        add: {
          price:1,
          path:""
        },
        fileList: [],
        formatFile: ".bmp,.jpg,.jpeg,.png,.gif",
        uploadTip: "格式只能为.bmp .jpg .jpeg .png .gif",
        addRules: {
          price: [{validator: checkPrice, trigger: 'blur'}]
        },
        //修改
        editDialogVisible: false,
        edit: {
          id: null,
          price:null,
          path:""
        },
        editImage: "",
        isShow: true,
        editFileList: [],
        editRules: {
          price: [{validator: checkPrice, trigger: 'blur'}]
        },
        // 删除
        delId: null,
        delDialogVisible: false,
        //分页
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    },
    mounted() {
      this.inquiryList();
    },
    methods: {
      isNotNull(value) {
        return value !== null && value !== undefined && value !== "";
      },
      //查询列表
      inquiryList() {
        let that = this;
        that.tableData = [];
        let data = {
          pageNumber: that.currentPage,
          pageSize: that.pageSize,
          filters: []
        };
        if (this.isNotNull(that.searchPath)) {  //路径
          data.filters.push({
            property: "path",
            value: that.searchPath,
            operator: "eq"
          })
        }
        if (this.isNotNull(that.searchId)) { //id
          data.filters.push({
            property: "id",
            value: that.searchId,
            operator: "eq"
          })
        }
        if (this.isNotNull(that.dateTimeRange)) { //时间
          data.filters.push({
            property: "create_date",
            value: that.dateTimeRange[0],
            operator: "ge"
          });
          data.filters.push({
            property: "create_date",
            value: that.dateTimeRange[1],
            operator: "le"
          })
        }
        request({
          method: 'post',
          url: 'admin/expression/list',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: data
        }).then(function (res) {
          if (res.code === 200) {
            that.total = res.data.total;
            let arr = res.data.records;
            if (arr.length === 0) {
              that.tableData = [];
            } else {
              that.tableData = arr
            }
          }
        }).catch(function (error) {
          console.log(error);
        });
      },
      //新增
      addUpload() {
        this.addDialogVisible = true;
      },
      addError(err, file, fileList) {
        this.fileList = [];
        this.editFileList = [];
      },
      addSuccess(res, file) {
        if (res.code === 200) {
          this.add.path = res.data.path;
        }
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleRemove(file, fileList) {
        this.fileList = [];
        this.editFileList = [];
        this.add.path = "";
        this.edit.path = "";
      },
      //文件超出个数限制
      handleExceed(files, fileList) {
        Message.warning('一次只能上传一个文件');
      },
      addSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let that = this;
            if (!that.add.path) {
              Message.warning('请选择需要上传的表情图片');
              return false;
            }
            request({
              method: 'post',
              url: 'admin/expression/save',
              data: that.add
            }).then(function (res) {
              if (res.code === 200) {
                that.addDialogVisible = false;
                Message.success("新增成功");
                that.$refs['addRuleForm'].resetFields();
                that.$refs.addUpload.clearFiles();
                that.inquiryList();
              }
            }).catch(function (error) {
              console.log(error);
            });
          } else {
            return false;
          }
        });
      },
      //修改
      editError(err, file, fileList) {
        this.fileList = [];
      },
      editSuccess(res, file) {
        if (res.code === 200) {
          this.edit.path = res.data.path;
          this.editImage = res.data.httpUrl;
          this.isShow = false;
        }
      },
      dealwithEdit(index, row) {
        this.editDialogVisible = true;
        this.edit = row;
        this.editImage = row.httpPath;
      },
      editSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let that = this;
            if (!that.edit.path) {
              Message.warning('请选择需要上传的表情图片');
              return false;
            }
            delete that.edit.createDate;
            delete that.edit.httpPath;
            delete that.edit.modifyDate;
            request({
              method: 'post',
              url: 'admin/expression/update',
              data: that.edit
            }).then(function (res) {
              if (res.code === 200) {
                that.editDialogVisible = false;
                Message.success("修改成功");
                that.inquiryList();
              }
            }).catch(function (error) {
              console.log(error);
            });
          } else {
            return false;
          }
        });
      },
      //删除
      dealwithDelete(index, row) {
        this.delDialogVisible = true;
        this.delId = row.id;
      },
      delKeys() {
        let that = this;
        that.delDialogVisible = false;
        request({
          method: 'post',
          url: 'admin/expression/delete/' + that.delId,
        }).then(function (res) {
          if (res.code === 200) {
            Message.success("删除成功");
            that.delId = null;
            that.inquiryList();
          }
        }).catch(function (error) {
          console.log(error);
        });
      },
      // 改变每页显示的数量
      handleSizeChange(val) {
        this.pageSize = val;
        this.inquiryList();
      },
      //改变当前页
      handleCurrentChange(val) {
        this.currentPage = val;
        this.inquiryList();
      }
    }
  }
</script>

<style src="../../assets/css/giftManagement/expressList.css">

</style>
